﻿using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;

namespace Casamiel.API
{
    /// <summary>
    /// Program.
    /// </summary>
    public class Program
    {
        /// <summary>
        /// The entry point of the program, where the program control starts and ends.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        public static void Main(string[] args)
        {
            int minWorker, minIOC;
            // Get the current settings.
            ThreadPool.GetMinThreads(out minWorker, out minIOC);

            Console.WriteLine($"minWorker:{minWorker}---minIOC:{minIOC}");
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetLogger("SystemErrorInfo");
            logger.Trace($"minWorker:{minWorker}---minIOC:{minIOC}");
            try
            {
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {

                logger.Error(ex, ex.Message);
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }

            //    .MigrateDbContext<CasamielContext>((context, services) =>
            //{
            //    var env = services.GetService<IHostingEnvironment>();
            //    var settings = services.GetService<IOptions<CasamielSettings>>();
            //    var logger = services.GetService<ILogger<OrderingContextSeed>>();

            //    new OrderingContextSeed()
            //        .SeedAsync(context, env, settings, logger)
            //        .Wait();
            //})
            //    .MigrateDbContext<IntegrationEventLogContext>((_, __) => { })
            //    .Run();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IHostBuilder CreateWebHostBuilder(string[] args) =>
       Host.CreateDefaultBuilder(args)
         .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.AllowSynchronousIO = true;
                })
                .UseStartup<Startup>().UseUrls("http://0.0.0.0:9982")
                        .ConfigureAppConfiguration((builderContext, config) =>
                        {
                            var env = builderContext.HostingEnvironment;
                            config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                            config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);

                        });

            });

    }
}
